﻿#include "statusnotification.h"
#include <QTimer>
#include <QEventLoop>
#include <thread>
#include "../../HttpServer/httpsend.h"
#include "systemconfiguration.h"

#include "component_log.h"
#include "componentmanager.h"

static void Sleep(int interval)
{
	if (interval < 50)
		interval = 50;
	QEventLoop loop;
	QTimer::singleShot(interval, [&loop]() {
		loop.quit();
		});

	loop.exec();
}

StatusNotification::StatusNotification(QObject* parent)
	: ComponentBase(parent)
{
	m_name = u8"系统状态发送组件";
	m_type = Component::component_stateSend;
	m_sh = nullptr;
}

StatusNotification::~StatusNotification()
{}

int StatusNotification::SetJointsInfo(const QByteArray& info)
{
	m_param.joints().fromJson(info);
	return 0;
}

/*初始化接口*/
int StatusNotification::ComponentInit()
{
	auto cfg = syscfg->GetWcsCfg();
	if (cfg.wcsIP.isEmpty()) {
		SetErrmsg(u8"配置的IP为空", false);
		return -99;
	}
	if (cfg.wcsport < 1) {
		SetErrmsg(u8"配置的端口号异常", false);
		return -99;
	}
	m_host = "http://" + cfg.wcsIP + ":" + QString::number(cfg.wcsport) + "/api/v1/wcs/robotStateInfo";

	auto robcfg = syscfg->GetRobotSetting();
	m_param.robNo = robcfg.id;

	auto rob = component->GetComponent(Component::component_robot);
	if (rob == nullptr) {
		log_error("get robot componet failed");
		return false;
	}
	// 订阅关节角度信息
	rob->RegisterSubscriberFunction((int)RobotCmdType::robot_cmd_get_joints, [&](const QByteArray& info) {
		return this->SetJointsInfo(info);
		});

	m_sh = component->GetComponent(Component::component_taskExcutor);
	if (m_sh == nullptr) {
		log_error("get TaskScheduler failed");
		return false;
	}

	m_sender = new HttpSend(this);
	m_timer.start();
	std::thread sendth(&StatusNotification::OnSendStateToWCS, this);
	if (sendth.joinable()) {
		sendth.detach();
	}

	return true;
}
/*自检接口*/
bool StatusNotification::ComponentCheckSelfState()
{
	return true;
}
/*复位接口*/
bool StatusNotification::ComponentSelfReset()
{
	m_param.errCode() = 0;
	m_param.errMsg() = "";
	return true;
}


void StatusNotification::ResponseSystemState(int event)
{
	m_param.sysState() = event;
	if (event == (int)SystemStateType::system_state_idle) {
		m_param.errCode = -1;
		m_param.errMsg = "系统启动中";
	} else 	if (event == (int)SystemStateType::system_state_stop) {
		m_param.errCode = -1;
		QString msg = component->GetErrorMsg();
		m_param.errMsg = msg;
	}
}


void StatusNotification::OnSendStateToWCS()
{
	while (1) {
		m_param.taskList().clear();
		QByteArray list; 
		m_sh->ExcuteCmd(2, {}, list);
		m_param.taskList() = QString(list).split(';');
	
		QByteArray data = m_param.toByteArray(QJsonDocument::Compact);
		//log_trace("state : {}", data);
		QByteArray ans;
		/*int ret = m_sender->SendPostMsgByHttp(m_host, data, ans, false);
		if (ret != 0) {
			log_error("send state failed");
		}*/
		Sleep(2000);
	}

}
